package com.tdcy.framework.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * 类名称：ReflectUtils 类描述：反射调用工具 创建人：qiuju 创建时间014-3-11 上午10:16:29
 * 
 * @version
 */
public final class ReflectUtils {

	/**
	 * @param methodObject
	 * @param methodName
	 *            方法
	 * @param args
	 *            方法名参数数
	 */
	@SuppressWarnings("unchecked")
	public static Object invokeMethod(Object methodObject, String methodName, Object[] args) throws Exception {
		Class ownerClass = methodObject.getClass();
		Class[] argsClass = new Class[args.length];
		for (int i = 0, j = args.length; i < j; i++) {
			argsClass[i] = args[i].getClass();
		}
		Method method = ownerClass.getMethod(methodName, argsClass);
		return method.invoke(methodObject, args);
	}

	/**
	 * @param methodObject
	 * @param methodName
	 *            方法
	 * @param args
	 *            方法名参数数
	 */
	@SuppressWarnings("unchecked")
	public static void invokeMethodNoReturn(Object methodObject, String methodName, Object[] args) throws Exception {
		Class ownerClass = methodObject.getClass();
		Class[] argsClass = new Class[args.length];
		for (int i = 0, j = args.length; i < j; i++) {
			argsClass[i] = args[i].getClass();
		}
		Method method = ownerClass.getMethod(methodName, argsClass);
		method.invoke(methodObject, args);
	}

	/**
	 * 
	 * @param cls
	 * @return
	 */
	public static List<Field> getParentClassFields(Class cls) {
		List<Field> list = new ArrayList<Field>();
		Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			list.add(field);
		}
		if (cls.getSuperclass() == null) {
			return list;
		}
		list.addAll(getParentClassFields(cls.getSuperclass()));
		return list;
	}

	/**
	 * 获取类属
	 * 
	 * @param cls
	 * @param includeParentClass
	 *            是否包含父类属
	 * @return
	 */
	public static List<Field> getClassFields(Class cls, boolean includeParentClass) {
		List<Field> list = new ArrayList<Field>();
		Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			list.add(field);
		}
		if (includeParentClass) {
			list.addAll(getParentClassFields(cls.getSuperclass()));
		}
		return list;
	}

	/**
	 * 获取类属
	 * 
	 * @param cls
	 * @param includeParentClass
	 *            是否包含父类属
	 * @return
	 */
	public static Field getFields(Class cls, String fieldName) {
		List<Field> list = getClassFields(cls, false);
		for (Field f : list) {
			if (f.getName().equals(fieldName)) {
				return f;
			}
		}

		return null;
	}
}
